# -*- coding: utf-8 -*-
# @Time    : 2022/5/22 16:23
# @Author  : zyw
# @Email   : panda_kings@163.com
# @File    : jwt_utils.py
import traceback

import jwt
from flask import current_app, g

from datetime import datetime, timedelta


def generate_jwt(payload):
    """
    生成jwt
    :param payload: dict 荷载信息
    :param expiry: date  有效期
    :param secret: str  盐
    :return:  token
    """
    try:
        secret = current_app.config['SECRET_KEY']
        # 生成token       _payload 荷载信息：用户账号信息、 有效期   secret 盐
        token = jwt.encode(payload, secret, algorithm='HS256')
        return token
    except Exception as e:
        error = traceback.format_exc()
        print('生成jwt token 错误:{}'.format(error))



def verify_jwt(token, secret=None):
    """
    校验token
    :param token: 需要校验的token
    :param secret: 盐
    :return: payload
    """
    payload = None
    if not secret:
        secret = current_app.config['SECRET_KEY']
    try:
        payload = jwt.decode(token, secret, algorithms='HS256')
    except:
        payload = None
    return payload


def _generate_token(payload, refresh=True):
    """
    生成token
    :param user_id:
    :return:    """

    # 定义过期时间
    expiry = datetime.utcnow() + timedelta(hours=2)
    payload["exp"] = expiry
    # 生成Token
    token = generate_jwt(payload,)
    return token


def refresh_token():
    """
    刷新token
    :return:
    """
    if g.account is not None and g.is_refresh is True:
        payload = {
            'account': g.account,
            'user_id': g.user_id,
            'is_refresh': False
        }
        token, _ = _generate_token(payload)
        return {'message': 'ok', 'data': {'token': token}, 'code': 200}
    else:
        return {'message': 'Invalid refresh token', 'code': 500}
